package com.mou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mou.entity.ChatBox;
import com.mou.entity.OnlineUser;
import com.mou.mapper.ChatMapper;
import com.mou.mapper.OnlineUserMapper;
import com.mou.service.OnlineUserService;
import com.mou.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("onlineUserService")
public class OnlineUserServiceImpl extends ServiceImpl<OnlineUserMapper, OnlineUser> implements OnlineUserService {

    @Autowired
    private OnlineUserMapper onlineUserMapper;
    @Autowired
    private ChatMapper chatMapper;

    @Override
    public void updateOnlineUser(OnlineUser onlineUser) {
        onlineUserMapper.updateOnlineUser(onlineUser);
    }

    @Override
    public void updateIsOnlineUser(OnlineUser onlineUser) {
        onlineUserMapper.updateIsOnline(onlineUser);
        // 构建WebSocket消息（JSON格式）
        ObjectMapper objectMapper = new ObjectMapper();
        String wsMessage;
        try {
            // 创建内层 data Map
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("content", onlineUser.getUserId() + "该用户已上线");
            dataMap.put("fromUserId", onlineUser.getUserId());
            dataMap.put("timestamp", LocalDateTime.now().toString());

            // 创建外层消息 Map
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("type", "CHAT_BOX");
            messageMap.put("data", dataMap);

            // 序列化为 JSON 字符串
            wsMessage = objectMapper.writeValueAsString(messageMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("消息序列化失败", e);
        }
        List<ChatBox> chatBox = chatMapper.getChatBox(onlineUser.getUserId());

        for(ChatBox box : chatBox){
            WebSocketServer.sendMessageToUser(
                    box.getReceiverId().toString(),
                    wsMessage
            );
        }
    }

    @Override
    public void updateNotOnlineUser(OnlineUser onlineUser) {
        onlineUserMapper.updateIsOnline(onlineUser);
        // 构建WebSocket消息（JSON格式）
        ObjectMapper objectMapper = new ObjectMapper();
        String wsMessage;
        try {
            // 创建内层 data Map
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("content", onlineUser.getUserId() + "该用户已下线");
            dataMap.put("fromUserId", onlineUser.getUserId());
            dataMap.put("timestamp", LocalDateTime.now().toString());

            // 创建外层消息 Map
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("type", "CHAT_BOX");
            messageMap.put("data", dataMap);

            // 序列化为 JSON 字符串
            wsMessage = objectMapper.writeValueAsString(messageMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("消息序列化失败", e);
        }
        List<ChatBox> chatBox = chatMapper.getChatBox(onlineUser.getUserId());

        for(ChatBox box : chatBox){
            WebSocketServer.sendMessageToUser(
                    box.getReceiverId().toString(),
                    wsMessage
            );
        }
    }
}
